<template>
  <div class="clt-root" v-loading="loading">

    <lark-card border card-title="采集排名" :x="500" :radius="false" v-if="ctlTaskVisible" :hidden="!ctlTaskVisible"
               body-width="800px" body-height="500px"
               @closeAction="ctlTaskVisible = !ctlTaskVisible" draggable>
      <div class="select-task-body">
        <ctl-rank></ctl-rank>
      </div>
    </lark-card>

    <lark-card border card-title="采集信息详情" :x="500" :radius="false" v-if="ctlSpeciesVisible" :hidden="!ctlSpeciesVisible"
               body-width="800px" body-height="500px"
               @closeAction="ctlSpeciesVisible = !ctlSpeciesVisible" draggable>
      <div class="select-task-body">
        <ctl-species></ctl-species>
      </div>
    </lark-card>
    <el-collapse-transition>
      <ctl-search @searchAction="searchAction" class="ctl-search"
                  v-show="!currentUserId || currentUserId === ''"></ctl-search>
    </el-collapse-transition>

    <ctl-task @rowClick="taskRowClick" class="ctl-task" ref="ctl-task"></ctl-task>
    <ctl-info @currentUserClick="currentUserClick" @ctlNumClick="searchAction({value:null,searchType:1})"
              @ctlUserClick="ctlTaskVisible=true"
              ref="ctl-result-info" class="ctl-info" @player="startPlayer"></ctl-info>

    <el-collapse-transition>
      <ctl-list @dataLoaded="dataLoaded" @rowClick="resultRowClick" v-if="listCardVisible" ref="ctl-list"
                @closeSelfAction="closeListAction"
                class="ctl-list"></ctl-list>
    </el-collapse-transition>

    <lark-map @loaded="mapLoaded" style="position: absolute" ref="mmap" :map-config="bufferMapConfig"
              :query-back-fun="queryBackFun"
              :before-query="beforeQuery"
              :after-query="afterQuery"></lark-map>

    <div style="display: none">
      <el-tabs v-model="activeUserName" ref="cltTabs">
        <el-tab-pane v-for="(item, index) in userData" :key="`${item.layerId}_${index}`" :label="item.layerName"
                     :name="item.layerId.toString()">
          <div class="table-container">
            <el-button roun @click="startPlayer" v-if="item.layerName === '采集人'" size="mini">轨迹播放</el-button>
            <lark-value-table :data="item.tableData" width="100%"
                              :height="item.layerName === '采集人'?'90%':'100%'" :column-number="2"></lark-value-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>


    <el-collapse-transition>
      <div class="player-container" :style="playerContainerStyle"
           v-if="mapView != null && currentUserId && currentUserId !== ''">
        <tack-play-back :view="mapView" :user-id="currentUserId"
                        :init-show="true" @load="setFinish" @exit="exitPlayer"></tack-play-back>
      </div>
    </el-collapse-transition>

    <div style="display: none">
      <div id="ppd" ref="ppd">
        <span style="font-size: 16px;color: #606266">此区域共采集 {{ plantPopData.length }}份数据</span>
        <el-table
          height="300"
          :data="plantPopData"
          stripe
          border
          style="width: 100%">
          <el-table-column
            prop="feature.attributes.NAME"
            label="名称"
            width="180">
          </el-table-column>
          <el-table-column
            prop="feature.attributes.CLT_USER_ID"
            label="采集人"
            width="180">
          </el-table-column>
          <el-table-column
            prop="feature.attributes.IDENTIFY_USER_ID"
            label="鉴定人">
          </el-table-column>
          <el-table-column
            prop="feature.attributes.CLT_TIME"
            label="采集日期">
          </el-table-column>
        </el-table>

        <div style="display: none">
          <el-tabs v-model="activeName" ref="ctabs">
            <el-tab-pane v-for="(item, index) in tabsData" :key="`${item.layerId}_${index}`" :label="item.layerName"
                         :name="item.layerId.toString()">
              <div class="table-container">
                <lark-value-table :data="item.tableData" width="100%"
                                  height="100%" :column-number="2"></lark-value-table>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>


        <!--        <div v-for="(item,index) in plantPopData" style="display: flex;align-items: center">-->
        <!--          <div>名称</div>-->
        <!--          <div>{{ item.feature.attributes.NAME }}</div>-->
        <!--          <div>采集人</div>-->
        <!--          <div>{{ item.feature.attributes.CLT_USER_ID }}</div>-->
        <!--          <div>鉴定人</div>-->
        <!--          <div>{{ item.feature.attributes.IDENTIFY_USER_ID }}</div>-->
        <!--          <div>采集日期</div>-->
        <!--          <div>{{ item.feature.attributes.CLT_TIME }}</div>-->
        <!--        </div>-->
      </div>

    </div>
  </div>
</template>

<script>
  import { reactive, toRefs, onMounted, ref, watch, computed, nextTick } from '@vue/composition-api'
  import ctlRank from './ctlSta/ctlRank'
  import ctlSpecies from './ctlSta/ctlSpecies'
  import ctlTask from './ctlTask'
  import ctlInfo from './ctlInfo'
  import ctlList from './ctlList'
  import ctlSearch from './ctlSearch'
  import mapConfig from '../../../../datas/cltMapConfig.json'
  import {
    getGraphicList,
    addGraphicLayer,
    getGraphic,
    getMapViewState,
    setMapViewState,
    getGraphicByGeometry,
    queryGraphicByAttribute,
    queryResultsByUrls,
    highlightByGeometryList,
    getGeometryListByQueryResult,
    getTabsDataByQueryResult,
    getOnlyResByQueryResult,
    removeHighlight,
    queryByGeometry,
    openPopup
  } from 'lark-map'
  import { onlineUser } from '@/api/industry/ctl'
  import { Message } from 'element-ui'
  import { MathUtil } from 'lark-utils'
  import tackPlayBack from '@/components/ServiceComponents/tackPlayBack/index'

  export default {
    name: 'clt',
    components: {
      ctlRank,
      ctlSearch,
      ctlList,
      ctlTask,
      ctlSpecies,
      ctlInfo,
      tackPlayBack
    },
    setup(props, content) {
      const playerContainerStyle = computed(() => {
        return { left: `${(window.innerWidth - 575) / window.innerWidth * 100 / 2}%` }
      })

      let data = reactive({
        ctlSpeciesVisible: false,
        listCardVisible: false,
        bufferMapConfig: mapConfig,
        mapView: null,
        onlineUserGraphicLayer: null,
        onlineUserNameGraphicLayer: null,
        plantGraphicLayer: null,
        ctlTaskVisible: false,
        loading: false,
        activeName: '',
        tabsData: [],
        plantPopData: [],
        currentLightUserGraphic: null,
        playerContainerStyle,
        currentUserId: '',
        finish: null,
        bufferUserId: '',
        userData: [],
        activeUserName: ''
      })

      const closeListAction = () => {
        data.listCardVisible = false
      }

      const currentUserClick = ({ id }) => {
        let { mapView: view } = data
        let graphic = queryGraphicByAttribute({ conditions: { id }, graphicLayer: data.onlineUserGraphicLayer })
        removeHighlight(view)
        if (graphic) {
          highlightByGeometryList({ view, geometryList: [graphic[0].geometry], zoom: true })
        }
      }

      const openRank = () => {
        data.ctlTaskVisible = true
      }

      /**
       * 向地图添加Graphic  Points
       * @param points {x,y,attributes}
       */
      const addGraphicPoints = (points, symbol, graphicLayer) => {
        if (!points) {
          return
        }
        let pointList = []
        for (let i = 0; i < points.length; i++) {
          let { x, y, attributes = {}, symbol: selfSymbol = null } = points[i]
          if (!x || !y) {
            continue
          }
          pointList.push({
            attributes: { ...attributes }, symbol: selfSymbol, geometryType: 'point', point: [x, y]
          })
        }

        let par = {
          config: pointList, spatialReference: {
            'wkid': 4490
          }
        }
        if (symbol) par.symbol = symbol

        let graphicList = getGraphicList(par)
        if (!graphicList) {
          return
        }
        if (graphicLayer) {
          graphicLayer.addMany(graphicList)
        } else {
          graphicLayer = addGraphicLayer({ view: data.mapView, graphicList: graphicList })
        }
        return graphicLayer
      }

      const dataLoaded = (items) => {

      }

      //加载地图上的采集信息
      const loadCtlData = async(conditions) => {
        console.log('conditions', conditions)
        const { mapView: view } = data
        let { NAME = null, AREA = null } = conditions
        let requestParams = {
          view,
          idList: [],
          outFields: [],
          where: [],
          returnGeometry: [],
          subLayerIds: []
        }
        let areaSubLayerId, value
        if (AREA) {
          let [province, city, county] = AREA
          if (county && county !== '') {
            areaSubLayerId = 2
            value = county
          }
          if (city && city !== '') {
            areaSubLayerId = 3
            value = city
          }
          if (province && province !== '') {
            areaSubLayerId = 4
            value = province
          }
          console.log(value)
          requestParams.idList.push('ChinaAdminService')
          requestParams.outFields.push({ parentId: 'ChinaAdminService', value: ['*'] })
          requestParams.where.push({ parentId: 'ChinaAdminService', value: `1=1 and CODE = ${value}` })
          requestParams.returnGeometry.push({ parentId: 'ChinaAdminService', value: true })
          requestParams.subLayerIds.push({ parentId: 'ChinaAdminService', value: [areaSubLayerId] })
        }
        if (NAME) {
          requestParams.idList.push('GermplasmResourceService')
          requestParams.outFields.push({ parentId: 'GermplasmResourceService', value: ['*'] })
          requestParams.where.push({ parentId: 'GermplasmResourceService', value: `1=1 and NAME LIKE '%${NAME}%'` })
          requestParams.returnGeometry.push({ parentId: 'GermplasmResourceService', value: true })
          requestParams.subLayerIds.push({ parentId: 'GermplasmResourceService', value: [0] })
        }

        if (requestParams.idList == []) {
          return
        }
        let res = await queryResultsByUrls(requestParams)
        let geometryList = getGeometryListByQueryResult({ res, merge: true })
        if (!geometryList?.length) {
          removeHighlight(view)
          return
        }
        highlightByGeometryList({ view, geometryList: getGeometryListByQueryResult({ res, merge: true }), zoom: true })

      }

      //适生区
      const loadPlantDistribute = async(conditions) => {
        data.loading = true
        try {
          const { mapView: view } = data
          let { NAME } = conditions
          let requestParams = {
            view,
            idList: [],
            outFields: [],
            where: [],
            returnGeometry: [],
            subLayerIds: []
          }
          if (NAME) {
            requestParams.idList.push('PlantSuitableRegionService')
            requestParams.outFields.push({ parentId: 'PlantSuitableRegionService', value: ['*'] })
            requestParams.where.push({
              parentId: 'PlantSuitableRegionService',
              value: `1=1 and NAME like  '%${NAME}%'`
            })
            requestParams.returnGeometry.push({ parentId: 'PlantSuitableRegionService', value: true })
            requestParams.subLayerIds.push({ parentId: 'PlantSuitableRegionService', value: [0] })
          }
          if (requestParams.idList == []) {
            return
          }
          let res = await queryResultsByUrls(requestParams)
          if (res[0].value.features.length == 0) {
            Message.info('未查询到任何信息')
            setMapViewState('unoccupied')
            return
          }
          if (!data.plantGraphicLayer) {
            data.plantGraphicLayer = addGraphicLayer({ view })
          }
          if (!res[0]?.value?.features?.length) {
            setMapViewState('unoccupied')
            return
          }
          //  设置地图状态
          setMapViewState('occupied')

          let graphics = res[0].value.features.map(item => {
            item.symbol = {
              type: 'simple-fill',
              color: [18, 252, 252, 0.1],
              outline: {
                color: [18, 252, 252, 1],
                width: 2
              }
            }
            return item
          })

          let graphicResUlt = []

          graphics.forEach(item => {
            if (item.geometry.rings[0].length <= 2) {
              graphicResUlt.push(item)
            } else {
              let { symbol, geometry: { rings, spatialReference }, attributes } = item
              rings.forEach(ring => {
                graphicResUlt.push(getGraphic({
                  geometryType: 'polygon',
                  attributes,
                  symbol,
                  rings: ring,
                  spatialReference
                }))
              })
            }
          })

          for (let i = 0; i < graphicResUlt.length; i++) {
            let currentGraphic = graphicResUlt[i]

            let qRes = await queryByGeometry({
              view,
              geometry: currentGraphic.geometry,
              idList: ['GermplasmResourceService'],
              returnFieldName: [{ parentId: 'GermplasmResourceService', value: false }],
              returnGeometry: [{ parentId: 'GermplasmResourceService', value: true }],
              layerOption: [{ parentId: 'GermplasmResourceService', value: 'visible' }],
              tolerance: [{ parentId: 'GermplasmResourceService', value: 0 }],
              subLayerIds: [{ parentId: 'GermplasmResourceService', value: [0] }]
            })

            if (!qRes?.length) {
              continue
            }

            let filterData = qRes[0].value.results.filter(it => {
              return currentGraphic.attributes.NAME === it.feature.attributes.NAME
            })

            if (filterData.length > 0) {
              let color
              if (filterData.length > 0 && filterData.length < 40) {
                color = [255, 255, 0, 1]
              } else if (filterData.length >= 40 && filterData.length < 80) {
                color = [0, 0, 255, 1]
              } else {
                color = [255, 0, 0, 1]
              }
              let bufferColor = JSON.parse(JSON.stringify(color))
              bufferColor[3] = 0.3
              currentGraphic.symbol = {
                type: 'simple-fill',
                color: bufferColor,
                outline: {
                  color: color,
                  width: 2
                }
              }
            }

          }

          data.plantGraphicLayer.addMany(graphicResUlt)
          view.goTo(graphics)
          // let geometryList = getGeometryListByQueryResult({ res, merge: true })
          // if (!geometryList?.length) {
          //   removeHighlight(view)
          //   return
          // }
          // highlightByGeometryList({ view, geometryList: getGeometryListByQueryResult({ res, merge: true }), zoom: true })

        } finally {
          data.loading = false
        }

      }

      const loadOnlineUser = async() => {

        let response = await onlineUser()
        let redata = response.data
        //更新当前采集人数
        if (content.refs['ctl-result-info']) {
          if (content.refs['ctl-result-info'].$refs['ctlNumRef']) {
            content.refs['ctl-result-info'].$refs['ctlNumRef'].setUserNum(redata.length)
          }
        }

        if (data.onlineUserGraphicLayer != null && data.onlineUserNameGraphicLayer != null) {
          redata = redata.filter(({ longitude, latitude, id, userId, nickName }) => {
            let graphic = queryGraphicByAttribute({ conditions: { id }, graphicLayer: data.onlineUserGraphicLayer })
            let textGraphic = queryGraphicByAttribute({
              conditions: { id },
              graphicLayer: data.onlineUserNameGraphicLayer
            })
            if (graphic != null && graphic.length > 0) {
              let { x, y } = graphic[0].geometry
              if (x != longitude || y != latitude) {
                //移除graphic,后面新增
                data.onlineUserGraphicLayer.remove(graphic[0])
                data.onlineUserNameGraphicLayer.remove(textGraphic[0])
                return true
              }
            }
            return false
          })
          data.onlineUserGraphicLayer.load()
        }

        if (redata.length == 0) return
        let points = redata.map(({ longitude: x, latitude: y, id, userId, nickName }) => {
          return { x, y, attributes: { id, userId, nickName } }
        })
        let symbol = {
          type: 'picture-marker',
          url: '',
          width: 28 / 1.5,
          height: 41 / 1.5,
          outline: true
        }
        //图像
        let gl = addGraphicPoints(points, symbol, data.onlineUserGraphicLayer)
        if (data.onlineUserGraphicLayer == null) {
          data.onlineUserGraphicLayer = gl
        }

        //文字
        let textPoints = JSON.parse(JSON.stringify(points)).map(t => {
          t.symbol = {
            type: 'text',  // autocasts as new TextSymbol()
            color: '#9065fa',
            haloColor: 'white',//给字体加框
            haloSize: '1px',
            text: t.attributes.nickName,
            xoffset: -1,
            yoffset: -20,
            font: {
              size: 12,
              family: 'microsoft-yahei',
              weight: 'bold'
            }
          }
          return t
        })
        let textgl = addGraphicPoints(textPoints, null, data.onlineUserNameGraphicLayer)
        if (data.onlineUserNameGraphicLayer == null) {
          data.onlineUserNameGraphicLayer = textgl
        }
      }
      const queryBackFun = (res, mapPoint) => {
        let { view } = data

        let onlyRes = getOnlyResByQueryResult({ res, mapPoint })

        if (!onlyRes?.length) {
          removeHighlight()
          return
        }

        let attList = getTabsDataByQueryResult(onlyRes)

        data.tabsData = attList.map(item => {

          let { tableData, layerId, layerName } = item

          let [currentTableData] = tableData

          let itemRes = {
            layerId: `${layerId}_${MathUtil.guid()}`,
            layerName
          }

          itemRes.tableData = Object.keys(currentTableData).filter(key => {
            let bufferKey = key.toUpperCase()
            return bufferKey !== 'OBJECTID' && bufferKey !== 'SHAPE' && bufferKey !== 'SHAPE.AREA' && bufferKey !== 'SHAPE.LEN' && bufferKey !== 'X' && bufferKey !== 'Y'
          }).map(key => {
            return { label: key, value: currentTableData[key] }
          })

          return itemRes
        })

        data.activeName = data.tabsData[0].layerId.toString()

        let geometryList = getGeometryListByQueryResult({ res: onlyRes, merge: true })
        highlightByGeometryList({ view, geometryList, zoom: false })

        return content.refs.ctabs.$el
      }

      const beforeQuery = () => {
        data.loading = true

      }

      const afterQuery = () => {
        data.loading = false

      }
      const mapLoaded = ({ mapView, mapType }) => {
        data.mapView = mapView
        loadOnlineUser()
        setInterval(() => {
          loadOnlineUser()
        }, 60000)

        mapView.on('click', async event => {
          let { mapView, onlineUserGraphicLayer: graphicLayer } = data

          let { mapPoint: geometry } = event

          let currentUser = getGraphicByGeometry({ graphicLayer, geometry })

          if (currentUser?.length) {
            data.bufferUserId = currentUser[0].attributes.userId

            data.userData = [{
              layerId: 0,
              layerName: '采集人',
              tableData: currentUser.map(item => {
                let { attributes: { nickName } } = item
                return { nickName }
              })
            }]

            openPopup({ view: mapView, location: geometry, popupContent: content.refs.cltTabs.$el, zoom: true })
            data.activeUserName = data.userData[0].layerId.toString()

            return
          } else {
            finishPlayer(true)
          }

          debugger
          if (!data.plantGraphicLayer?.graphics?.items?.length) return

          let pg = getGraphicByGeometry({ graphicLayer: data.plantGraphicLayer, geometry })
          if (!pg?.length) return

          let [{ geometry: queryGeometry }] = pg

          let res = await queryByGeometry({
            view: mapView,
            geometry: queryGeometry,
            idList: ['GermplasmResourceService'],
            returnFieldName: [{ parentId: 'GermplasmResourceService', value: false }],
            returnGeometry: [{ parentId: 'GermplasmResourceService', value: true }],
            layerOption: [{ parentId: 'GermplasmResourceService', value: 'visible' }],
            tolerance: [{ parentId: 'GermplasmResourceService', value: 0 }],
            subLayerIds: [{ parentId: 'GermplasmResourceService', value: [0] }]
          })

          let filterData = res[0].value.results.filter(it => {
            let result = pg.filter(p =>
              it.feature.attributes.NAME == p.attributes.NAME
            )
            if (result.length > 0) {
              return true
            }
          })
          removeHighlight(data.mapView)
          highlightByGeometryList({
            view: mapView,
            geometryList: getGeometryListByQueryResult({ res: [{ value: { results: filterData } }], merge: true }),
            zoom: true
          })
          data.plantPopData = filterData
          nextTick((() => {
            console.log(content.refs.ppd)
            openPopup({ view: mapView, location: geometry, popupContent: content.refs.ppd, zoom: true })
          }))

        })

      }
      const resultRowClick = (id) => {
        nextTick(() => {
          content.refs['ctl-result-info'].queryById(id)
        })
      }

      const taskRowClick = (item) => {
        data.listCardVisible = true
        nextTick(() => {
          content.refs['ctl-list'].taskQuery(item)
        })
      }
      const searchAction = (item) => {
        console.log('searchAction', item)
        if (data.mapView) {
          removeHighlight(data.mapView)
        }
        if (data.plantGraphicLayer) {
          data.plantGraphicLayer.removeAll()
        }
        let { location: AREA = null, value: NAME = null } = item
        if (item.searchType == 1) {
          setMapViewState('unoccupied')
          //采集信息
          loadCtlData({ AREA, NAME })
          data.listCardVisible = true
          nextTick(() => {
            content.refs['ctl-list'].inputQuery(item)
          })
        } else if (item.searchType == 2) {
          //适生区域
          loadPlantDistribute({ NAME })
        }
      }

      const setFinish = ({ finish }) => {
        data.finish = finish
      }

      const finishPlayer = finishFlag => {
        if (finishFlag && data.finish && typeof data.finish === 'function' && data.currentUserId && data.currentUserId !== '') {
          data.finish(false)
        }

        if (content.refs['ctl-result-info']?.$refs?.drawer?.noOffAction && data.currentUserId !== '') {
          content.refs['ctl-result-info'].$refs.drawer.noOffAction()
        }

        if (content.refs['ctl-task']?.$refs?.drawer?.noOffAction && data.currentUserId !== '') {
          content.refs['ctl-task'].$refs.drawer.noOffAction()
        }

        data.currentUserId = ''
        data.bufferUserId = ''
      }

      const startPlayer = userId => {
        let { mapView: view } = data
        view.popup.close()
        closeListAction()

        if (content.refs['ctl-result-info']?.$refs?.drawer?.offAction) {
          content.refs['ctl-result-info'].$refs.drawer.offAction()
        }

        if (content.refs['ctl-task']?.$refs?.drawer?.offAction) {
          content.refs['ctl-task'].$refs.drawer.offAction()
        }

        setTimeout(() => {
          data.currentUserId = typeof userId === 'string' && userId !== '' ? userId : data.bufferUserId
        }, 5)
      }

      const exitPlayer = () => {
        finishPlayer()
      }

      return {
        ...toRefs(data),
        closeListAction,
        taskRowClick,
        searchAction,
        resultRowClick,
        mapLoaded,
        dataLoaded,
        loadCtlData,
        queryBackFun,
        beforeQuery,
        afterQuery,
        openRank,
        currentUserClick,
        setFinish,
        exitPlayer,
        startPlayer
      }
    },
    beforeRouteLeave(to, from, next) {
      setMapViewState('unoccupied')
      next()
    }
  }
</script>

<style lang="scss">
  $full: 100%;
  $top: 3vh;
  .clt-root {
    position: relative;
    height: $full;

    .ctlSearch-root {

      .lark-card-root {
        .lark-card__body {

          .input-search {
            .el-input-group__append {
              border: none;
            }
          }

          .more-search {
          }
        }
      }
    }

    .ctl-search, .ctl-task, .ctl-list, .ctl-info {
      position: absolute;
      z-index: 10;
    }

    .ctl-search, .ctl-task, .ctl-info {
      top: $top;
    }

    .ctl-search {
      left: 42%;
    }

    .ctl-task {
    }

    .ctl-list {
      bottom: 0;
      left: 20%;
    }

    .ctl-info {
      right: 0;
    }

    .player-container {
      position: absolute;
      bottom: 20px;
      z-index: 20;
      display: flex;
      flex-direction: row;
    }
  }
</style>
